package com.mc.mcgoweb.aop;

import com.mc.common.annotation.IgnoreDupKeyException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

/***
 * @ClassName IgnoreDupKeyAop
 * @Description 防止重复性校验AOP
 * @Author CC
 * @Date: 2019/3/21 9:23
 * @Version 1.0
 */

@Aspect
@Component
@Order(3)
public class IgnoreDupKeyAop {
//    @Autowired
//    private IDuplicateDataDao duplicateDataDao;

    /**
     * 切所有加幂等性注解的操作
     */
    @Pointcut("@annotation(com.mc.common.annotation.IgnoreDupKeyException)")
    public void doValidate() {
    }

    /**
     * 环绕切入
     */
    @Around("doValidate()")
    public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        IgnoreDupKeyException annotation = ((MethodSignature) signature).getMethod().getAnnotation(IgnoreDupKeyException.class);
        String annotationValue = annotation.value();
        String[] valueArray = annotationValue.split("\\.");
        String key = "";
        for (Object arg : args) {
            Class<?> aClass = arg.getClass();
            key = getFilterKey(valueArray, key, arg, aClass);
            break;
        }
//        DuplicateDataFilter duplicateDataByKey = duplicateDataDao.findDuplicateDataByKey(key);
//        if (duplicateDataByKey != null) {
////            throw new BusinessException("重复执行操作！");
//            return ResultUtil.getFailureResultData("重复执行操作");
//        }
//        DuplicateDataFilter dataFilter = new DuplicateDataFilter();
//        dataFilter.setFilterKey(key);
//        dataFilter.setCreateTime(new Date());
//        duplicateDataDao.add(dataFilter);
        return joinPoint.proceed();

    }

    private String getFilterKey(String[] valueArray, String key, Object arg, Class<?> aClass) throws NoSuchFieldException, IllegalAccessException {
        for (String fieldName : valueArray) {
            Field field = aClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            Object o = field.get(arg);
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(o.toString())) {
                key = o.toString();
            } else if (!StringUtils.isEmpty(o.toString())) {
                key = key + "-" + o.toString();
            }
        }
        return key;
    }

}
